// src/error/ErrorBoundary.js
import React, { Component } from 'react';

class ErrorBoundary extends Component {
  state = { hasError: false, error: null };
  
  static getDerivedStateFromError(error) {
    return { hasError: true, error };
  }
  
  componentDidCatch(error, errorInfo) {
    console.error('组件渲染错误:', error, errorInfo);
    
    // 特别处理DOM相关错误
    if (error.message.includes('removeChild') || error.message.includes('Node')) {
      console.warn('检测到DOM操作错误，尝试强制清理DOM');
      this.forceCleanDOM();
    }
  }
  
  forceCleanDOM = () => {
    // 尝试安全清理DOM元素
    const container = document.querySelector('.safe-er-diagram-container');
    if (container) {
      container.innerHTML = '';
    }
  };
  
  handleRetry = () => {
    this.setState({ hasError: false, error: null });
  };
  
  render() {
    if (this.state.hasError) {
      return (
        <div className="error-boundary">
          <h3>ER图组件渲染出错</h3>
          <p>{this.state.error && this.state.error.toString()}</p>
          <p>错误通常发生在组件卸载过程中，已尝试修复</p>
          <button onClick={this.handleRetry}>重试渲染</button>
        </div>
      );
    }
    
    return this.props.children;
  }
}

export default ErrorBoundary;